package com.delayqueue.core.netty.handler.registry;

import com.alibaba.fastjson.JSON;
import com.delayqueue.common.enums.MessageType;
import com.delayqueue.common.netty.NettyMessage;
import com.delayqueue.core.cache.NodeCacheFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

public class RegistryMessageHandler extends SimpleChannelInboundHandler<NettyMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, NettyMessage message) throws Exception {

        MessageType messageType = message.getMessageType();
        String messageContent = message.getMessageContent();
        if (messageType == MessageType.MASTER_ALL) {
            List<String> list = JSON.parseArray(messageContent, String.class);
            list.forEach(s -> {
                String[] ipPort = s.split(":");
                NodeCacheFactory.master.add(ipPort[0], Integer.parseInt(ipPort[1]));
            });
        } else if (messageType == MessageType.MASTER_ONLINE) {
            String[] ipPort = messageContent.split(":");
            NodeCacheFactory.master.add(ipPort[0], Integer.parseInt(ipPort[1]));
        } else if (messageType == MessageType.MASTER_OFFLINE) {
            String[] ipPort = messageContent.split(":");
            NodeCacheFactory.master.delete(ipPort[0], Integer.parseInt(ipPort[1]));
        }
    }
}
